<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: SuperMan <superman@itkee.cn>
// +----------------------------------------------------------------------
use think\Db;
// 应用公共文件
// header('Content-Type:text/plain;charset=utf-8');
/**
 * 生成二维码
 * @param string $url
 */
function get_qr_code($url = ''){
    Vendor('phpqrcode');
    $value = $url;         //二维码内容
    $errorCorrectionLevel = 'L';  //容错级别
    $matrixPointSize = 5;      //生成图片大小

    // 判断是否有这个文件夹  没有的话就创建一个
    if(!is_dir("qrcode")){
        // 创建文件加
        mkdir("qrcode");
    }
    //设置二维码图片名称，以及存放的路径
    $filename = 'qrcode/'.time().rand(10000,9999999).'.png';
    //使用类库生成二维码
    QRcode::png($value,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
//　如果需要转换成base64数据，解开下面这行注释即可
//　$image_data = chunk_split(base64_encode(fread(fopen($filename, 'r'), filesize($filename))));
//二维码路径
    return '/'.$filename;

}

/**
 *  上传文件
 * @param string $name  input name值
 * @param string $path  保存路径
 * @return img路径
 */
function upload_file($name='file',$path='uedit/image'){
    $config = [
        'size' => 2097152000,
        'ext'  => 'jpg,png,gif,jpeg'
    ];
    $file = request()->file($name);
    if($file){
        $upload_path = str_replace('\\', '/', ROOT_PATH . "uploads/{$path}/");
        $save_path   = "/uploads/{$path}/";
        $info        = $file->validate($config)->move($upload_path);
        if ($info) {
            return str_replace('\\', '/', $save_path . $info->getSaveName());
        } else {
            return false;
            //$file->getError()
        }
    }
}
/**
 * 发送邮件
 * @param string $address
 * @param string $subject
 * @param string $message
 * @return array<br>
 * 返回格式：<br>
 * array(<br>
 * 	"error"=>0|1,//0代表出错<br>
 * 	"message"=> "出错信息"<br>
 * );
 */
function send_mail($mail_to, $mailsubject, $mailbody,$id){
	Vendor('PHPMailer.PHPMailerAutoload');
    $email_config = db('system')->field('value')->where('name', 'email_config')->find();
	$email_config = unserialize($email_config['value']);
	$address = explode(',',$mail_to);
	
    $mail = new \PHPMailer; //https://github.com/PHPMailer/PHPMailer
    //$mail->SMTPDebug = 3;                         // 启用详细的调试输出
    $mail->isSMTP();                                // 设置邮件程序使用SMTP
    $mail->Host = $email_config['smtp'];                       // 指定主服务器和备份SMTP服务器
    $mail->SMTPAuth = true;                         // 启用SMTP验证
    $mail->CharSet = "UTF-8";                       // 设置邮件编码
    $mail->Username = $email_config['loginname'];               // SMTP username，发件箱
    $mail->Password = $email_config['password'];               // SMTP password，发件箱密码
	$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 465;                                 // TCP port to connect to
    $mail->AddAttachment("uploads/word/resumes".$id.".docx"); // 添加附件
    $mail->setFrom($email_config['loginname'],$email_config['sender']);                 //发件人
	foreach($address as $v){
		$mail->addAddress($v);                    // 添加收件人,名称是可选的
	}
    $mail->isHTML(true);                            // 将电子邮件格式设置为HTML
    $mail->Subject = $mailsubject;
    $mail->Body    = $mailbody;
    //halt($mailbody);
    if(!$mail->send()) {
        return false;		
        //return 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        return true;
    }
}

/*function send_mail1($mail_to, $mailsubject, $mailbody){
    Vendor('PHPMailer.PHPMailerAutoload');
    $email_config = db('system')->field('value')->where('name', 'email_config')->find();
    $email_config = unserialize($email_config['value']);
//    halt($email_config);
    $address = explode(',',$mail_to);

    $mail = new \PHPMailer; //https://github.com/PHPMailer/PHPMailer
    $mail->SMTPDebug = 3;                         // 启用详细的调试输出
    $mail->isSMTP();                                // 设置邮件程序使用SMTP
//    $mail->Host = 'smtp.exmail.qq.com';                       // 指定主服务器和备份SMTP服务器
    $mail->Host = 'smtp.263.net';                       // 指定主服务器和备份SMTP服务器
    $mail->SMTPAuth = true;                         // 启用SMTP验证
    $mail->CharSet = "UTF-8";                       // 设置邮件编码
    $mail->Username = 'jianli@hrnew.com';               // SMTP username，发件箱
    $mail->Password = 'abc12345678';               // SMTP password，发件箱密码
//    $mail->Username = "jiangyang@huisheng.com";               // SMTP username，发件箱
//    $mail->Password = "........";               // SMTP password，发件箱密码
    $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 465;                                 // TCP port to connect to
//    $mail->AddAttachment("uploads/word/resume".$id.".docx"); // 添加附件
    $mail->setFrom('jiangyang@huisheng.com','jy');                 //发件人
    foreach($address as $v){
        $mail->addAddress($v);                    // 添加收件人,名称是可选的
    }
    $mail->isHTML(true);                            // 将电子邮件格式设置为HTML
    $mail->Subject = $mailsubject;
    $mail->Body    = $mailbody;
    if(!$mail->send()) {
        // return false;
        return 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        return true;
    }
}*/

/**
 * 发送邮件
 * @param string $address
 * @param string $subject
 * @param string $message
 * @return array<br>
 * 返回格式：<br>
 * array(<br>
 * 	"error"=>0|1,//0代表出错<br>
 * 	"message"=> "出错信息"<br>
 * );
 */
function send_qz_mail($mail_to, $mailsubject, $mailbody,$time){
    Vendor('PHPMailer.PHPMailerAutoload');
    $email_config = db('system')->field('value')->where('name', 'email_config')->find();
    $email_config = unserialize($email_config['value']);
    $address = explode(',',$mail_to);

    $mail = new \PHPMailer; //https://github.com/PHPMailer/PHPMailer
    //$mail->SMTPDebug = 3;                         // 启用详细的调试输出
    $mail->isSMTP();                                // 设置邮件程序使用SMTP
    $mail->Host = $email_config['smtp'];                       // 指定主服务器和备份SMTP服务器
    $mail->SMTPAuth = true;                         // 启用SMTP验证
    $mail->CharSet = "UTF-8";                       // 设置邮件编码
    $mail->Username = $email_config['loginname'];               // SMTP username，发件箱
    $mail->Password = $email_config['password'];               // SMTP password，发件箱密码
    $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 465;                                 // TCP port to connect to
    $mail->AddAttachment('public/static/index/word/'.$time.'.docx'); // 添加附件
    $mail->setFrom($email_config['loginname'],$email_config['sender']);                 //发件人
    foreach($address as $v){
        $mail->addAddress($v);                    // 添加收件人,名称是可选的
    }
    $mail->isHTML(true);                            // 将电子邮件格式设置为HTML
    $mail->Subject = $mailsubject;
    $mail->Body    = $mailbody;
    if(!$mail->send()) {
        // return false;
        return 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        return true;
    }
}

/**
 * 加密函数
 * @param string $txt 需要加密的字符串
 * @param string $key 密钥
 * @return string 返回加密结果
 */
function encrypt($txt, $key = ''){
    if (empty($txt)) return $txt;
    if (empty($key)) $key = md5(\think\Config::get('salt'));
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $nh1 = rand(0,64);
    $nh2 = rand(0,64);
    $nh3 = rand(0,64);
    $ch1 = $chars{$nh1};
    $ch2 = $chars{$nh2};
    $ch3 = $chars{$nh3};
    $nhnum = $nh1 + $nh2 + $nh3;
    $knum = 0;$i = 0;
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum%8,$knum%8 + 16);
    $txt = base64_encode(time().'_'.$txt);
    $txt = str_replace(array('+','/','='),array('-','_','.'),$txt);
    $tmp = '';
    $j=0;$k = 0;
    $tlen = strlen($txt);
    $klen = strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = ($nhnum+strpos($chars,$txt{$i})+ord($mdKey{$k++}))%64;
        $tmp .= $chars{$j};
    }
    $tmplen = strlen($tmp);
    $tmp = substr_replace($tmp,$ch3,$nh2 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch2,$nh1 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch1,$knum % ++$tmplen,0);
    return $tmp;
}

/**
 * 解密函数
 * @param string $txt 需要解密的字符串
 * @param string $key 密匙
 * @return string 字符串类型的返回结果
 */
function decrypt($txt, $key = '', $ttl = 0){
    if (empty($txt)) return $txt;
    if (empty($key)) $key = md5(\think\Config::get('salt'));

    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $knum = 0;$i = 0;
    $tlen = @strlen($txt);
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $ch1 = @$txt{$knum % $tlen};
    $nh1 = strpos($chars,$ch1);
    $txt = @substr_replace($txt,'',$knum % $tlen--,1);
    $ch2 = @$txt{$nh1 % $tlen};
    $nh2 = @strpos($chars,$ch2);
    $txt = @substr_replace($txt,'',$nh1 % $tlen--,1);
    $ch3 = @$txt{$nh2 % $tlen};
    $nh3 = @strpos($chars,$ch3);
    $txt = @substr_replace($txt,'',$nh2 % $tlen--,1);
    $nhnum = $nh1 + $nh2 + $nh3;
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum % 8,$knum % 8 + 16);
    $tmp = '';
    $j=0; $k = 0;
    $tlen = @strlen($txt);
    $klen = @strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = strpos($chars,$txt{$i})-$nhnum - ord($mdKey{$k++});
        while ($j<0) $j+=64;
        $tmp .= $chars{$j};
    }
    $tmp = str_replace(array('-','_','.'),array('+','/','='),$tmp);
    $tmp = trim(base64_decode($tmp));

    if (preg_match("/\d{10}_/s",substr($tmp,0,11))){
        if ($ttl > 0 && (time() - substr($tmp,0,11) > $ttl)){
            $tmp = null;
        }else{
            $tmp = substr($tmp,11);
        }
    }
    return $tmp;
}
/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}
/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $table = 'nav', $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $son = Db::name($table)->where(['pid'=>$v['id']])->count('id');
            $son?$v['son'] = true:$v['son'] = false;
            $list[]     = $v;
            array2level($array, $table, $v['id'], $level + 1 );
        }
    }

    return $list;
}

/**
 * 构建层级（树状）数组
 * @param array  $array          要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid_name       父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = 'pid', $child_key_name = 'children')
{
    $counter = array_children_count($array, $pid_name);
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid_name] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid_name], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid_name);
    }

    return $tree;
}

/**
 * 子元素计数器
 * @param array $array
 * @param int   $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name)
{
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}

/**
 * 获取客户端IP地址
 * @param integer   $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean   $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function ip($type = 0, $adv = false)
{
    $type      = $type ? 1 : 0;
    static $ip = null;
    if (null !== $ip) {
        return $ip[$type];
    }

    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }
            $ip = trim(current($arr));
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? [$ip, $long] : ['0.0.0.0', 0];
    return $ip[$type];
}

/**
 * @param $data
 * @return bool
 * 是否为序列化数据
 */
function is_serialized( $data ) {
    $data = trim( $data );
    if ( 'N;' == $data )
        return true;
    if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
        return false;
    switch ( $badions[1] ) {
        case 'a' :
        case 'O' :
        case 's' :
            if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
                return true;
            break;
        case 'b' :
        case 'i' :
        case 'd' :
            if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
                return true;
            break;
    }
    return false;
}

/**
 * 不区分大小写的in_array实现
 * @param mixed 待搜索的值。
 * @param array 待搜索的数组。
 * @return boolean  如果找到则返回 TRUE，否则返回 FALSE。
 */
function in_array_case($value,$array){
    return in_array(strtolower($value),array_map('strtolower',$array));
}

/**
 * 截取中文字符串
 * @param $str  待处理字符串
 * @param int $start    开始位置
 * @param $length   长度
 * @param string $charset   字符集
 * @param bool $suffix  增加...
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
    $str = strip_tags($str);//去除html和php标签
    //$str = preg_replace('/\s/','',$str);//去除\s
    if(function_exists("mb_substr")){
        $slice= mb_substr($str, $start, $length, $charset);
    }elseif(function_exists('iconv_substr')) {
        $slice= iconv_substr($str,$start,$length,$charset);
    }else{
        $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
        $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
        $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
        $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }    
    $fix='';
    if(strlen($slice) < strlen($str)){
        $fix='...';
    }
    return $suffix ? $slice.$fix : $slice;
}

/**
 * 生成参数位随机数
 * @param int $length 生成字符串长度
 * @return string
 */
function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

/**
 * 获取面包屑
 * @param $id   当前导航id
 * @param string $str   字符串引用值
 * @return string   返回面包屑
 */
function crumbs($id,&$str=''){
    $nav = db('nav')->field('id,pid,name')->find($id);
    $str = '><a href="'.url($nav['link'],$nav['pid']==0?['fid'=>$nav['id']]:['nid'=>$nav['id']]).'">'.$nav['name'].'</a>'.$str;
    if($nav['pid']!=0) crumbs($nav['pid'],$str);
    return $str;
}

/**
 * 获取当前导航的最顶层导航id
 * @param $id   当前导航id
 * @return mixed    返回最顶层id
 */
function base_pid($id){
    $nav = db('nav')->field('id,pid')->find($id);
    while ($nav['pid']!=0){
        $nav = db('nav')->field('id,pid')->find($nav['pid']);
    }
    return $nav['id'];
}

/**
 * 根据键给二维数组分组
 * @param $arr  二维数组
 * @param $key  键
 * @return array    返回分组后数组
 */
function array_group_by($arr, $key)
{
    $grouped = [];
    foreach ($arr as $value) {
        $grouped[$value[$key]][] = $value;
    }
    if (func_num_args() > 2) {
        $args = func_get_args();
        foreach ($grouped as $key => $value) {
            $parms = array_merge([$value], array_slice($args, 2, func_num_args()));
            $grouped[$key] = call_user_func_array('array_group_by', $parms);
        }
    }
    return $grouped;
}

/**
 * curl GET
 * @param $url
 * @return mixed
 */
function httpGet($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 50);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}

/**
 * curl POST
 * @param $url
 * @param $data
 * @return mixed
 */
function httpPost($url,$data){
    //以上方式获取到的数据是json格式的
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    // post数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // post的变量
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

/**
 * 转换所有HTML实体
 * @param $str  输入字符
 * @param string $enc   字符编码
 * @return string   返回转换后的字符
 */
function HShtmlentities($str,$enc='UTF-8'){
    return htmlentities($str, ENT_QUOTES, $enc);   //UTF-8防止中文乱码
}
if (!function_exists('pd')) {
    // 传递数据以易于阅读的样式格式化后输出并终止
    function pd($data, $toArray = true)
    {
        p($data, $toArray);
        die;
    }
}
if (!function_exists('p')) {
    //传递数据以易于阅读的样式格式化后输出
    function p($data){
        // 定义样式
        $str='<pre style="display: block;padding: 9.5px;margin: 44px 0 0 0;font-size: 13px;line-height: 1.42857;color: #333;word-break: break-all;word-wrap: break-word;background-color: #F5F5F5;border: 1px solid #CCC;border-radius: 4px;">';
        // 如果是boolean或者null直接显示文字；否则print
        if (is_bool($data)) {
            $show_data=$data ? 'true' : 'false';
        }elseif (is_null($data)) {
            $show_data='null';
        }else{
            $show_data=print_r($data,true);
        }
        $str.=$show_data;
        $str.='</pre>';
        echo $str;
    }
}
if ( !function_exists('re_substr') ) {
    /**
     * 字符串截取，支持中文和其他编码
     *
     * @param string  $str 需要转换的字符串
     * @param integer $start 开始位置
     * @param string  $length 截取长度
     * @param boolean $suffix 截断显示字符
     * @param string  $charset 编码格式
     * @return string
     */
    function re_substr($str, $start = 0, $length, $suffix = true, $charset = "utf-8") {
        $slice = mb_substr($str, $start, $length, $charset);
        $omit = mb_strlen($str) >= $length ? '...' : '';
        return $suffix ? $slice.$omit : $slice;
    }
}

/**
 * 数组转xls格式的excel文件
 * @param  array  $data      需要生成excel文件的数组
 * @param  string $filename  生成的excel文件名
 *      示例数据：
        $data = array(
            array(NULL, 2010, 2011, 2012),
            array('Q1',   12,   15,   21),
            array('Q2',   56,   73,   86),
            array('Q3',   52,   61,   69),
            array('Q4',   30,   32,    0),
           );
 */
function create_xls($data,$filename='simple.xls'){
    ini_set('max_execution_time', '0');
    Vendor('PHPExcel.PHPExcel');
    $filename=str_replace('.xls', '', $filename).'.xls';
    $phpexcel = new PHPExcel();
    $phpexcel->getProperties()
        ->setCreator("Maarten Balliauw")
        ->setLastModifiedBy("Maarten Balliauw")
        ->setTitle("Office 2007 XLSX Test Document")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory("Test result file");
    $phpexcel->getActiveSheet()->fromArray($data);
    $phpexcel->getActiveSheet()->setTitle('Sheet1');
    $phpexcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=$filename");
    header('Cache-Control: max-age=0');
    header('Cache-Control: max-age=1');
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
    $objwriter->save('php://output');
    exit;
}
//企业微信******************************************************************


/**获取企业ID
 * @return string
 */
function get_appId(){
    return 'ww504cd4efd92e6407';
}

/**获取自建应用ID
 * @return string
 */
function get_agentid(){
    return '1000002';
}
/**获取自建应用密钥
 * @return string
 */
function get_appSecret(){
    return 'EIC4p_7CodzcO-Zx617xn54qZsUYaB5giR3V9otNWR0';
}
/**获取
 * @return mixed
 */
function get_access_token(){
    $file = file_get_contents("./access_token.json",true);
    $result = json_decode($file,true);
    if(time() > $result['expires']){
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.get_appId().'&corpsecret='.get_appSecret();
        $token = json_decode(httpGet($url),true);
        $data['access_token'] = $token['access_token'];
        $data['expires']=time()+$token['expires_in']-200;
        $jsonStr =  json_encode($data);
        file_put_contents("./access_token.json", $jsonStr);
        return $data['access_token'];
    }else{
        return $result['access_token'];
    }
}
function get_access_token1(){
    $file = file_get_contents("./access_token1.json",true);
    $result = json_decode($file,true);
    if(time() > $result['expires']){
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.get_appId().'&corpsecret='.get_appSecret();
        $token = json_decode(httpGet($url),true);
        $data['access_token'] = $token['access_token'];
        $data['expires']=time()+$token['expires_in']-200;
        $jsonStr =  json_encode($data);
        file_put_contents("./access_token1.json", $jsonStr);
        return $data['access_token'];
    }else{
        return $result['access_token'];
    }
}
/**获取用户信息
 * @param $userid
 * @return mixed
 */
function get_user_info($userid){
    $data = model('user')->where('user_id','=',$userid)->find();
    return $data;
    $url = $get_userid_url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='. get_access_token() . '&userid=' .$userid;
    $res = httpGet($url);
    $res= json_decode($res,true);
    return $res;
}

/**获取部门列表
 * @return mixed
 */
function get_department_list(){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='.get_access_token();
    $res= httpGet($url);
    $res = json_decode($res,true);
    return $res;
}
function get_department_list_id($id){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='.get_access_token().'&id='.$id;
    $res= httpGet($url);
    $res = json_decode($res,true);
    return $res;
}
function get_user_list($id,$fe=1){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token='.get_access_token().'&department_id='.$id.'&fetch_child='.$fe;
    $res= httpGet($url);
    $res = json_decode($res,true);
    return $res;
}

/** 根据部门获取成员列表
 * @param $department_id
 * @param int $fetch_child
 * @return mixed
 */
function get_userlist_bydepartmentid($department_id,$fetch_child=1){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token='.get_access_token().'&department_id='.$department_id.'&fetch_child='.$fetch_child;
    $res= httpGet($url);
    $res= json_decode($res,true);
    return $res;
}
/**获取js ticket
 * @return mixed
 */
function get_jsapi_ticket(){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token='.get_access_token();
    $res= httpGet($url);
    $res= json_decode($res,true);
    return $res;
}

/**
 * @param $touser
 * @param $title
 * @param $description
 * @param $url
 * @return mixed
 */
function send_message_templete($touser,$title,$description,$return){
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.get_access_token();
    $data=[
        "touser"=>implode('|',$touser),
        "msgtype"=>"textcard",
        "agentid"=>get_agentid(),
        "textcard"=>[
            "title"=>$title,
            "description"=>$description,
            "url"=>$return,
            "btntxt"=>"详情"
        ]
    ];
    $data = json_encode($data);
    $res= httpPost($url,$data);
    $res= json_decode($res,true);
    return $res;

}






/**
 * 用于模型中返回处理结果（验证及执行的判断）
 * @param int $code     返回码，1成功，0失败
 * @param string $msg 提示语
 * @param string $url 需跳转的url
 * @return array
 * @internal param string $data 返回数据
 */
function ajax_return($code,$msg,$url = ''){
    if ($url=='' && !is_null($_SERVER['HTTP_REFERER']) && $code==1) {   //成功时有跳转url，失败仅提示
        $url = $_SERVER['HTTP_REFERER'];
    } elseif ('' !== $url){
        $url = url($url);
    }
    $result = ['code' => $code, 'msg'  => $msg, 'url'  => $url];
    return $result;
}

/**
 * 过滤表情
 */
if (!function_exists('filterEmoji')) {

    // 过滤掉emoji表情
    function filterEmoji($str)
    {
        $str = preg_replace_callback(    //执行一个正则表达式搜索并且使用一个回调进行替换
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }
}

/**
 * 根据尺寸压缩图片
 * @param $url //图片的相对路径
 * @param $maxwidth //设置图片的最大宽度
 * @param $maxheight //设置图片的最大高度
 * @return array //图片压缩后路径
 */
function resizeImage($url,$maxwidth=0,$maxheight=0)
{
//    $web = model('System')->getValue('upload_config');
    $web['img_resize']='on';
    $web['img_resize_opt']=2;
    if($web['img_resize']=='on'){   //开启图片压缩后，上传后调整图片大小
        if(!extension_loaded('gd')){
            return ['error' => 1,'message' => '请开启gd扩展'];
        }
        /*if($maxwidth<1 || $maxheight<1){
            return ['error' => 1,'message' => '请设置图片最大宽高']; //ie10以下获取不到传参
        }*/
        //$file_name = substr($url,strripos($url,"/")+1);
        //$filetype = strtolower(substr($file_name,strripos($file_name,".")+1));  //后缀名
        //$name = substr($url,0,strrpos($url,".")).'_resize.';   //不含后缀的文件名
        $name = $url;//$name.$filetype;
        //1 = GIF，2 = JPG，3 = PNG，6 = BMP，15 = WBMP，16 = XBM。
        $type = getimagesize($url)[2];   //图片的类型，即使修改后缀

        //png图片直接返回原图路径，png透明图片会导致压缩后图片改变
        if($type==3)return ['error' => 0,'url' => ltrim($url,'.')];

        switch ($type){
            case 1:
                $im = imagecreatefromgif($url);
                break;
            case 2:
                $im = imagecreatefromjpeg($url);
                break;
            case 3:
                $im = imagecreatefrompng($url);
                break;
            case 15:
                $im = imagecreatefromwbmp($url);
                break;
            case 6:
                $im = $this->imagecreatefrombmp($url);
                break;
        }

        $pic_width = imagesx($im);
        $pic_height = imagesy($im);
        //开启推荐尺寸等比缩小，并且宽高有任一大于推荐尺寸才进行缩小
        if($web['img_resize_opt']==2 && (($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)))
        {
            if($maxwidth && $pic_width>$maxwidth)
            {
                $widthratio = $maxwidth/$pic_width;
                $resizewidth_tag = true;
            }

            if($maxheight && $pic_height>$maxheight)
            {
                $heightratio = $maxheight/$pic_height;
                $resizeheight_tag = true;
            }

            if($resizewidth_tag && $resizeheight_tag)
            {
                if($widthratio<$heightratio)
                    $ratio = $widthratio;
                else
                    $ratio = $heightratio;
            }

            if($resizewidth_tag && !$resizeheight_tag)
                $ratio = $widthratio;
            if($resizeheight_tag && !$resizewidth_tag)
                $ratio = $heightratio;

            $newwidth = $pic_width * $ratio;
            $newheight = $pic_height * $ratio;

            if(function_exists("imagecopyresampled"))
            {
                $newim = imagecreatetruecolor($newwidth,$newheight);
                imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP系统函数
            }
            else
            {
                $newim = imagecreate($newwidth,$newheight);
                imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
            }

            switch ($type){
                case 1:
                    imagegif($newim,$name);
                    break;
                case 2:
                    imagejpeg($newim,$name);
                    break;
                case 3:
                    imagepng($newim,$name);
                    break;
                case 15:
                    imagewbmp($newim,$name);
                    break;
                default:
                    imagejpeg($newim,$name);
                    break;
            }
            imagedestroy($newim);
        }
        else
        {//仅压缩图片
            switch ($type){
                case 2:
                    imagejpeg($im,$name);
                    break;
                case 3:
                    imagepng($im,$name);
                    break;
                case 15:
                    imagewbmp($im,$name);
                    break;
                default:
                    imagejpeg($im,$name);
                    break;
            }
        }
        if(is_file($name)){
            return ['error' => 0,'url' => ltrim($name,'.')];
        }
    }
    //未开启图片压缩、压缩后无图片，等原因返回原图路径
    return ['error' => 0,'url' => ltrim($url,'.')];
}